import React, { useEffect, useRef, useState } from "react";
import {
  Form,
  Row,
  Col,
  Button,
  Space,
  Input,
  message,
  Spin,
  Select,
} from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { uploadMemoryInfo, updateMemoryInfo } from "@/api/api_memory";
import { changeupdateState } from "@/store/modules/assStore";
const type = "Memory";

interface ChildMethods {
  handleUpload: () => void;
}

function MemoryItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const [form] = Form.useForm();
  useEffect(() => {
    if (!isAdd) {
      const { manufacturers, capacity, type, frequency, price, score } =
        assInfo;
      const data = {
        memoryManufacturer: manufacturers,
        memoryType: type,
        memoryCapacity: capacity,
        memoryFrequency: frequency,
        price,
        score,
      };
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);

  //Memory TSX
  const MEMORY = {
    MANUFACTURERS: (
      <Form.Item
        name="memoryManufacturer"
        label="内存厂商"
        rules={[
          {
            required: true,
            message: "Please select your memoryManufacturer!",
          },
        ]}
      >
        <Input />
      </Form.Item>
    ),
    TYPE: (
      <Form.Item
        name="memoryType"
        label="内存类型"
        rules={[
          {
            required: true,
            message: "Please select your memoryType!",
          },
        ]}
      >
        <Select
          options={[
            { value: "DDR3", label: "DDR3" },
            { value: "DDR4", label: "DDR4" },
            { value: "DDR5", label: "DDR5" },
            { value: "DDR6", label: "DDR6" },
            { value: "DDR6X", label: "DDR6X" },
            { value: "other", label: "其他" },
          ]}
        />
      </Form.Item>
    ),
    CAPACITY: (
      <Form.Item
        name="memoryCapacity"
        label="内存容量"
        rules={[
          {
            required: true,
            message: "Please select your memoryCapacity!",
          },
        ]}
      >
        <Select
          options={[
            { value: "8", label: "8GB" },
            { value: "16", label: "16GB" },
            { value: "32", label: "32GB" },
            { value: "64", label: "64GB" },
            { value: "128", label: "128GB" },
            { value: "other", label: "其他" },
          ]}
        />
      </Form.Item>
    ),
    FREQUENCY: (
      <Form.Item
        name="memoryFrequency"
        label="内存频率"
        rules={[
          {
            required: true,
            message: "Please select your memoryFrequency!",
          },
        ]}
      >
        <Input suffix="MHz" />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };

  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  const dispatch = useAppDispatch();

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();
    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加Center信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.memoryManufacturer,
        type: values.memoryType,
        capacity: values.memoryCapacity,
        frequency: values.memoryFrequency,
        img_url_arr,
        price: parseFloat(values.price),
        score: parseFloat(values.score),
      };
      if (!isAdd) {
        await updateMemoryInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadMemoryInfo(info);
        message.success("添加成功");
      }
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{MEMORY.MANUFACTURERS}</Col>
          <Col span={12}>{MEMORY.TYPE}</Col>
          <Col span={12}>{MEMORY.CAPACITY}</Col>
          <Col span={12}>{MEMORY.FREQUENCY}</Col>
          <Col span={12}>{MEMORY.SCORE}</Col>
          <Col span={12}>{MEMORY.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              添加
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default MemoryItem;
